package com.tarena.lbs.basic.web.dao.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.dao.mapper.AdminMapper;
import com.tarena.lbs.basic.web.pojo.param.AddAdminParam;
import com.tarena.lbs.basic.web.pojo.param.QueryAdminParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;


@Repository
public class AdminRepository extends ServiceImpl<AdminMapper, AdminPO> {

    @Autowired
    private AdminMapper adminMapper;



    @NotNull
    public List<AdminVO> getAdminVOS(QueryAdminParam queryAdminParam, PageResult<AdminVO> pageResult) {
        Page<AdminPO> page = new Page<>(queryAdminParam.getPageNo(),queryAdminParam.getPageSize());

        QueryWrapper<AdminPO> queryWrapper = getQueryWrapper(queryAdminParam);
        Page<AdminPO> page1 = this.page(page, queryWrapper);

        pageResult.setTotal(page1.getTotal());
        List<AdminPO> records = page1.getRecords();
        List<AdminVO> collect = records.stream().map(item -> {
            AdminVO adminVO = new AdminVO();
            BeanUtils.copyProperties(item, adminVO);
            return adminVO;
        }).collect(Collectors.toList());
        return collect;
    }

    private QueryWrapper<AdminPO> getQueryWrapper(QueryAdminParam queryAdminParam) {
        QueryWrapper<AdminPO> queryWrapper = new QueryWrapper<>();
        if (queryAdminParam.getAccountPhone() != null) {
            queryWrapper.eq("account_phone",queryAdminParam.getAccountPhone());
        }
        if (queryAdminParam.getNickname() != null) {
            queryWrapper.like("nickname",queryAdminParam.getNickname());
        }

        return queryWrapper;
    }

    public Boolean existsAdminPOByAccountPhone(String accountPhone) {
        return this.lambdaQuery().eq(AdminPO::getAccountPhone,accountPhone).exists();
    }

    public Boolean existsAdminPOByEmail(String email) {
        return this.lambdaQuery().eq(AdminPO::getEmail,email).exists();
    }




    public void check(AddAdminParam addAdminParam) throws BusinessException {
        //查询是否存在手机号
        Boolean b1 = this.existsAdminPOByAccountPhone(addAdminParam.getAccountPhone());
        if (b1){
            throw new BusinessException("-2","手机号或邮箱已存在");
        }
        //查询是否存在邮箱
        Boolean b2 = this.existsAdminPOByEmail(addAdminParam.getEmail());
        if (b2){
            throw new BusinessException("-2","手机号或邮箱已存在");
        }

    }
}
